<template>
  <!-- 工单通知配置表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="800px"
      draggable
      align-center
      @close="closeDialog"
    >
      <el-form
        v-show="!props.isReadonly"
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
      >
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="工序" prop="processId" style="width: 100%">
                <el-select
                  v-model="formData.processId"
                  placeholder="请选择工序"
                  clearable
                >
                  <el-option
                    v-for="item in processList"
                    :key="item.id"
                    :label="`${item.processCode}`"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="过程质量监控分类"
                prop="abilityType"
                style="width: 100%"
              >
                <el-select
                  v-model="formData.abilityType"
                  placeholder="请选择过程质量监控分类"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in useDictionary('AbilityType')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks" style="width: 100%">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.remarks"
                  type="textarea"
                  placeholder="请输入备注"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <el-descriptions
        v-show="props.isReadonly"
        title=""
        :column="2"
        size="large"
        border
        style="
          width: 99%;
          max-height: 70vh;
          overflow-y: auto;
          margin-bottom: 15px;
        "
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">工序</div>
          </template>
          {{ formData.processCode || "" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">过程质量监控分类</div>
          </template>
          {{ useDictionary("AbilityType", formData.abilityType) || "" }}
        </el-descriptions-item>
        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">备注</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.remarks || "暂无备注" }}
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <el-tabs v-model="tabKey" type="border-card" style="width: 100%">
        <el-tab-pane
          v-for="(item, index) in tabsArray"
          :label="item.label"
          :key="index"
          :name="item.name"
        >
          <el-button
            type="success"
            plain
            @click="handleAddPerson(item.name)"
            v-if="!props.isReadonly"
            class="mb-[10px]"
          >
            <i-ep-plus />
            新增
          </el-button>
          <div class="formTable">
            <el-table
              :data="item.tableData"
              style="width: 100%"
              :key="Math.random"
              max-height="360px"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                min-width="80"
              />
              <el-table-column
                label="角色"
                props="roleName"
                min-width="150"
                align="center"
              >
                <template #default="{ $index, row }">
                  <span>{{ row.roleName }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="角色对应用户"
                props="roleName"
                min-width="300"
                align="left"
              >
                <template #default="{ $index, row }">
                  <div
                    v-for="(item, index) in userMap[row.roleId]?.map(
                      (item) => `${item.firstName}: ${item.email}`
                    )"
                  >
                    {{ item }}
                  </div>
                </template>
              </el-table-column>

              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                min-width="100"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    type="danger"
                    link
                    @click.stop="
                      handleDeletePerson(scope.$index, item.tableData)
                    "
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <pcmworkordernotice-select
      :visible="selectDialogPerson.visible"
      :data="breakListPerson"
      :title="selectDialogPerson.title"
      @change-visible-person="changeVisiblePerson"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "PCMPCMWORKORDERNOTICEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  processId: "",
  processName: "",
  processCode: "",
  abilityType: "",
  responsibleRoleList: "",
  leaderRoleList: "",
  remarks: "",
  details: [],
});

/** rules规则 */
const rules = reactive({
  processId: [{ required: true, message: "请选择工序", trigger: "blur" }],
  abilityType: [
    { required: true, message: "请选择过程质量监控分类", trigger: "blur" },
  ],
  remarks: [],
  sonroleName: [],
});

const isValidated = ref(false);
/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      getdetails();
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
  tabsArray.value.forEach((item) => (item.tableData = []));
  tabKey.value = "notice";
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.processId = "";
  formData.processCode = "";
  formData.processName = "";
  formData.abilityType = "";
  formData.responsibleRoleList = "";
  formData.leaderRoleList = "";
  formData.remarks = "";
  formData.details = [];
}

const loading = ref(false);

/** 工单通知配置保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      const process = processList.value.find(
        (item: any) => item.id === formData.processId
      );
      formData.processName = process?.processName;
      formData.processCode = process?.processCode;
      formData.details = tabsArray.value.flatMap((item: any) => item.tableData);
      console.log("formData", toRaw(formData));
      await request({
        url: "/dmpDosPcm/pcmworkordernotice/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

const processList: any = ref([]);
async function getProcessCodeList() {
  const { data } = await request({
    url: `/mdm/mdmprocess/getList`,
    method: "post",
    data: {},
  });
  processList.value = data;
}
onMounted(() => {
  getProcessCodeList();
  getUserList();
});

const tabKey = ref("notice");

const tabsArray = ref([
  {
    name: "notice",
    label: "通知权限",
    tableData: [],
    roleType: 1,
  },
  {
    name: "edit",
    label: "编辑权限",
    tableData: [],
    roleType: 2,
  },
  {
    name: "approval",
    label: "审批权限",
    tableData: [],
    roleType: 3,
  },
  {
    name: "finalApproval",
    label: "最终审批权限",
    tableData: [],
    roleType: 4,
  },
]);

const selectDialogPerson = reactive({
  visible: false,
  title: "",
  changeName: "",
});

// 新增完返回的数据用于显示选择器
const breakListPerson = ref([]);
const getBreakListPerson = (tableData) => {
  breakListPerson.value = [];
  tableData.forEach((item) => {
    breakListPerson.value.push({
      id: item.roleId,
      roleName: item.roleName,
    });
  });
};

const handleAddPerson = (name) => {
  selectDialogPerson.title = "选择角色";

  selectDialogPerson.visible = true;
  selectDialogPerson.changeName = name;
  const find = tabsArray.value.find(
    (item) => item.name == selectDialogPerson.changeName
  );
  getBreakListPerson(find.tableData);
};
const handleDeletePerson = (index: any, tableData) => {
  tableData.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};
const changeVisiblePerson = (val: boolean, data: any) => {
  if (data) {
    const find = tabsArray.value.find(
      (item) => item.name == selectDialogPerson.changeName
    );
    find.tableData.length = 0;
    data.forEach((item) => {
      find?.tableData.push({
        roleId: item.id,
        roleName: item.roleName,
        roleType: find.roleType,
      });
    });
  }
  selectDialogPerson.visible = val;
};

const userMap = ref();

const getUserList = async () => {
  await request({
    url: "/system/sysUser/getUserEmailsByRoleId",
    method: "get",
    params: { roleIds: "" },
  }).then(({ data }) => {
    userMap.value = data.reduce((acc, item) => {
      const roleId = item.roleId;
      acc[roleId] = acc[roleId] || [];
      acc[roleId].push(item);
      return acc;
    }, {});
    console.log("userMap", userMap.value);
  });
};

async function getdetails() {
  formData.details = [];
  let sondetails = await request({
    url: "/dmpDosPcm/pcmworkordernotice/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  const detailMap = sondetails.data.reduce((acc, item) => {
    const roleType = item.roleType;
    acc[roleType] = acc[roleType] || [];
    acc[roleType].push(item);
    return acc;
  }, {});
  tabsArray.value.forEach(
    (item) => (item.tableData = detailMap[item.roleType])
  );
}
</script>

<style lang="scss" scoped></style>
